package com.egdigital.allzic.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.text.SpannableStringBuilder;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCacheManager;
import com.egdigital.allzic.push.PushManager;
import com.egdigital.allzic.utils.MemoryManager;
import com.egdigital.allzic.utils.Utils;

public class ActivitySetting extends SherlockPreferenceActivity {

	private static final String	TAG	= ActivitySetting.class.getSimpleName();	// log
	private ActionBar			mActionBar;
	private Preference			mMemory;
	private Preference			mVersion;
	private Preference			mApropos;
	private Preference			mFavoris;
	private Preference			mLicence;

	// private CheckBoxPreference mPush;
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// allow music volume
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		// update orientation restrictions
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if (prefs.getBoolean("orientation_all", true)) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		}
		// actionbar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true);
		// preferences
		addPreferencesFromResource(R.xml.activity_preference);
//		mPush = (CheckBoxPreference) findPreference("push");
		mMemory = (Preference) findPreference("memory");
		mVersion = (Preference) findPreference("version");
		mApropos = (Preference) findPreference("apropos");
		mFavoris = (Preference) findPreference("favoris");
		mLicence = (Preference) findPreference("licence");
		PreferenceManager.setDefaultValues(this, R.xml.activity_preference, false);
		setupListeners();
		setupContent();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				finish();
				overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.slide_from_behind, R.anim.slide_out_right);
	}

	private void setupListeners() {
		// mPush.setOnPreferenceClickListener(new OnPreferenceClickListener() {
		//
		// @Override
		// public boolean onPreferenceClick(Preference preference) {
		// PushManager.getInstance(getApplicationContext());
		// PushManager.registerGCM();
		// return true;
		// }
		// });
		mApropos.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				openDialog(getString(R.string.dialog_confirm_nav), getString(R.string.url_allzic_site));
				return true;
			}
		});
		mLicence.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				Intent intent = new Intent(ActivitySetting.this, ActivityLegalInformation.class);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
				return true;
			}
		});
		mFavoris.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				onpenDialogClearCache();
				return true;
			}
		});
	}

	private void openDialog(String text, final String url) {
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(url));
						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						break;
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(text).setPositiveButton("Oui", dialogClickListener).setNegativeButton("Non", dialogClickListener).show();
	}

	private void onpenDialogClearCache() {
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						JsonCacheManager.ClearCache(getApplicationContext(), JsonCacheManager.RECENT_STATION);
						JsonCacheManager.ClearCache(getApplicationContext(), JsonCacheManager.FAVORITE_STATION);
						JsonCacheManager.ClearCache(getApplicationContext(), JsonCacheManager.FAVORITE_CATEGORY);
						Utils.customToast(new SpannableStringBuilder(getString(R.string.setting_clear_cache_success)), getApplicationContext(), false);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						break;
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.dialog_confirm_cache)).setPositiveButton("Oui", dialogClickListener).setNegativeButton("Non", dialogClickListener).show();
	}

	private void setupContent() {
		Long memoryAvailable;
		Long memoryTotal;
		memoryAvailable = MemoryManager.getAvailableInternalMemorySize();
		memoryTotal = MemoryManager.getTotalInternalMemorySize();
		if (MemoryManager.externalMemoryAvailable()) {
			memoryAvailable = +MemoryManager.getAvailableExternalMemorySize();
			memoryTotal = +MemoryManager.getTotalExternalMemorySize();
		}
		mMemory.setSummary(MemoryManager.formatSize(memoryAvailable) + " / " + MemoryManager.formatSize(memoryTotal));
		// version
		try {
			mVersion.setSummary("" + (getPackageManager().getPackageInfo(getPackageName(), 0).versionName));
		} catch (NameNotFoundException e) {
			mVersion.setSummary(" /");
		}
	}
}
